<html><head><meta charset="utf-8"><title>21 使用 Webpack 的 Tree-Shaking-慕课专栏</title>
			<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
			<meta name="renderer" content="webkit">
			<meta property="qc:admins" content="77103107776157736375">
			<meta property="wb:webmaster" content="c4f857219bfae3cb">
			<meta http-equiv="Access-Control-Allow-Origin" content="*">
			<meta http-equiv="Cache-Control" content="no-transform ">
			<meta http-equiv="Cache-Control" content="no-siteapp">
			<link rel="apple-touch-icon" sizes="76x76" href="https://www.imooc.com/static/img/common/touch-icon-ipad.png">
			<link rel="apple-touch-icon" sizes="120x120" href="https://www.imooc.com/static/img/common/touch-icon-iphone-retina.png">
			<link rel="apple-touch-icon" sizes="152x152" href="https://www.imooc.com/static/img/common/touch-icon-ipad-retina.png">
			<link href="https://moco.imooc.com/captcha/style/captcha.min.css" rel="stylesheet">
			<link rel="stylesheet" href="https://www.imooc.com/static/moco/v1.0/dist/css/moco.min.css?t=201907021539" type="text/css">
			<link rel="stylesheet" href="https://www.imooc.com/static/lib/swiper/swiper-3.4.2.min.css?t=201907021539">
			<link rel="stylesheet" href="https://static.mukewang.com/static/css/??base.css,common/common-less.css?t=2.5,column/zhuanlanChapter-less.css?t=2.5,course/inc/course_tipoff-less.css?t=2.5?v=201907051055" type="text/css">
			<link charset="utf-8" rel="stylesheet" href="https://www.imooc.com/static/lib/ueditor/themes/imooc/css/ueditor.css?v=201907021539"><link rel="stylesheet" href="https://www.imooc.com/static/lib/baiduShare/api/css/share_style0_16.css?v=6aba13f0.css"></head>
			<body><div id="main">

<div class="container clearfix" id="top" style="display: block; width: 1134px;">
    
    <div class="center_con js-center_con l" style="width: 1134px;">
        <div class="article-con">
                            <!-- 买过的阅读 -->
                <div class="map">
                    <a href="/read" target="_blank"><i class="imv2-feather-o"></i></a>
                    <a href="/read/29" target="_blank">Webpack 从零入门到工程化实战</a>
                    <a href="" target="_blank">
                        <span>
                            / 3-5 21 使用 Webpack 的 Tree-Shaking
                        </span>
                    </a>
                </div>

            


            <div class="art-title" style="margin-top: 0px;">
                21 使用 Webpack 的 Tree-Shaking
            </div>
            <div class="art-info">
                
                <span>
                    更新时间：2019-06-24 09:32:52
                </span>
            </div>
            <div class="art-top">
                                <img src="https://img1.mukewang.com/5cd9641e0001c6c306390359.jpg" alt="">
                                                <div class="famous-word-box">
                    <img src="https://www.imooc.com/static/img/column/bg-l.png" alt="" class="bg1 bg">
                    <img src="https://www.imooc.com/static/img/column/bg-r.png" alt="" class="bg2 bg">
                    <div class="famous-word">你若要喜爱你自己的价值，你就得给世界创造价值。<p class="author">——歌德</p></div>
                </div>
                            </div>
            <div class="art-content js-lookimg">
                <div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">Tree-Shaking 是一个前端术语，本意为摇树的意思，在前端术语中通常用于描述移除 JavaScript 上下文中没用的代码，这样可以有效地缩减打包体积。关于 Tree-Shaking，Webpack 官方文档有一段很形象的描述：</p>
</div><div class="cl-preview-section"><blockquote>
<p style="font-size: 20px; line-height: 38px;">你可以将应用程序想象成一棵树。绿色表示实际用到的源码和 library，是树上活的树叶。灰色表示无用的代码，是秋天树上枯萎的树叶。为了除去死去的树叶，你必须摇动这棵树，使它们落下。<br>
<img src="http://img.mukewang.com/5d0c3ee100018fa304120232.gif" alt="图片描述" data-original="http://img.mukewang.com/5d0c3ee100018fa304120232.gif" class="" style="cursor: pointer;"></p>
</blockquote>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">Tree-Shaking 最早是由 Rich Harris 在打包工具 <a href="https://rollupjs.org/">rollup.js</a>提出并且实现的，其实在更早，Google Closure Compiler 也做过类似的事情。在 Webpack 2 中吸取了 Tree-Shaking 功能，并且在 Webpack 中得到实现。</p>
</div><div class="cl-preview-section"><h2 id="tree-shaking-实现原理" style="font-size: 30px;">Tree-Shaking 实现原理</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">Tree-Shaking 的本质是消除无用的 JavaScript 代码。无用代码消除（Dead Code Elimination）广泛存在于传统的编程语言编译器中，编译器可以判断出某些代码根本不影响输出，然后消除这些代码，这个称之为 DCE（Dead Code Elimination）。Tree-Shaking 是 DCE 的一种新的实现，Javascript 同传统的编程语言不同的是，JavaScript 绝大多数情况是在浏览器中执行，需要通过网络进行加载，然后解析 JavaScript 文件再执行。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">2018 年年中，据 HTTP Archive 统计：移动端 JavaScript 文件的平均传输大小将近 350KB。你要知道，这仅仅是传输的大小。在网络传输的时候，JavaScript 往往是经过压缩的。也就是说，在浏览器解压缩之前，实际的大小会远远大于这个值。而这一点相当重要。如果考虑到浏览器处理数据的资源消耗，其中压缩是不得不考虑的。一个 300KB 的文件解压缩会达到 900KB，并且在分析和编译的时候，体积依然是 900KB。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><img src="http://img.mukewang.com/5d0760130001c44208260174.jpg" alt="图片描述" data-original="http://img.mukewang.com/5d0760130001c44208260174.jpg" class="" style="cursor: pointer;"><br>
由于网络的带宽限制，加载的 JavaScript 文件体积越小，整体解析执行时间更短，所以去除无用代码以减少文件体积，对 JavaScript 来说更有意义。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">Tree-Shaking 和传统的 DCE 的方法又不太一样，传统的 DCE 消灭不可能执行的代码：</p>
</div><div class="cl-preview-section"><ul>
<li style="font-size: 20px; line-height: 38px;">程序中没有执行的代码，如不可能进入的分支，<code>return</code> 之后的语句等；</li>
<li style="font-size: 20px; line-height: 38px;">导致 dead variable 的代码，写入变量之后不再读取的代码。</li>
</ul>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">和 DCE 不同的是，Tree-Shaking 则更关注于消除没有用到的代码。通过之前的章节介绍过，Webpack 是基于 ES6 Modules 静态语法解析的构建工具，Tree-Shaking 之所以能够在 Webpack 实现，也是得益于 ES6 Modules 静态解析的特性。ES6 的模块声明保证了依赖关系是提前确定的，使得静态分析成为可能，这样在 Webpack 中代码不需要执行就可以知道是否被使用，自然就知道哪些是无用的代码了。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">ES6 Modules 特点：</p>
</div><div class="cl-preview-section"><ul>
<li style="font-size: 20px; line-height: 38px;">ES6 中<code>import</code>和<code>export</code>是显性声明的；</li>
<li style="font-size: 20px; line-height: 38px;">import 的模块名只能是字符串常量；</li>
<li style="font-size: 20px; line-height: 38px;">ES6 模块的依赖关系是可以根据<code>import</code>引用关系推导出来的。</li>
<li style="font-size: 20px; line-height: 38px;">ES6 模块的依赖关系与运行时状态无关</li>
</ul>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">上面这些 ES6 Modules 的特点是 Tree-Shaking 的基础。所谓静态分析就是不执行代码，从字面量上对代码进行分析，ES6 之前的模块化，比如我们可以动态 require 一个模块，只有执行后才知道引用的什么模块，这个就不能通过静态分析去做优化。这是 ES6 Modules 在设计时的一个重要考量，也是为什么没有直接采用 CommonJS，正是基于这个基础上，才使得 Tree-Shaking 成为可能，这也是为什么 rollup.js 和 Webpack 2 都要用 ES6 Module 语法才能实现 Tree-Shaking。</p>
</div><div class="cl-preview-section"><h2 id="webpack-tree-shaking-代码实战" style="font-size: 30px;">Webpack Tree-Shaking 代码实战</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">在 Webpack 中，Tree-Shaking 是需要配合<code>mode=production</code>来使用的，这是因为 Webpack 的 Tree-Shaking 实际分了两步来实现：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">Webpack 自己来分析 ES6 Modules 的引入和使用情况，去除不使用的<code>import</code>引入；</li>
<li style="font-size: 20px; line-height: 38px;">借助工具（如 <code>uglifyjs-webpack-plugin</code>和<code>terser-webpack-plugin</code>）进行删除，这些工具只在<code>mode=production</code>中会被使用。</li>
</ol>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们通过实例来看下这两个步骤，首先我们准备了两个文件：<code>utils.js</code>和<code>index.js</code>文件，其中<code>utils.js</code>中定义了两个方法<code>isNull</code>和<code>isNumber</code>：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token comment">// utils.js</span>
<span class="token keyword">export</span> <span class="token keyword">function</span> <span class="token function">isNull</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'isNull'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token keyword">null</span> <span class="token operator">===</span> obj<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">export</span> <span class="token keyword">function</span> <span class="token function">isNumber</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'isNumber'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">return</span> <span class="token keyword">typeof</span> obj <span class="token operator">===</span> <span class="token string">'number'</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">但是在<code>index.js</code>中<code>import</code>了<code>utils</code>的两个函数方法，但是实际却只用了<code>isNull</code>的方法：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token comment">// index.js</span>
<span class="token keyword">import</span> <span class="token punctuation">{</span>isNull<span class="token punctuation">,</span> isNumber<span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'./utils'</span><span class="token punctuation">;</span>

<span class="token function">isNull</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">下面我们使用<code>webpack --mode=development</code>打包看下结果：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token punctuation">{</span>
<span class="token string">'./src/index.js'</span><span class="token punctuation">:</span> <span class="token keyword">function</span><span class="token punctuation">(</span>module<span class="token punctuation">,</span> __webpack_exports__<span class="token punctuation">,</span> __webpack_require__<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token string">'use strict'</span><span class="token punctuation">;</span>
    <span class="token comment">// 注意！注意！注意！</span>
    <span class="token comment">// 注意这里打包后_utils__WEBPACK_IMPORTED_MODULE_0__</span>
    __webpack_require__<span class="token punctuation">.</span><span class="token function">r</span><span class="token punctuation">(</span>__webpack_exports__<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">/* harmony import */</span> <span class="token keyword">var</span> _utils__WEBPACK_IMPORTED_MODULE_0__ <span class="token operator">=</span> <span class="token function">__webpack_require__</span><span class="token punctuation">(</span>
        <span class="token comment">/*! ./utils */</span> <span class="token string">'./src/utils.js'</span>
    <span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token function">Object</span><span class="token punctuation">(</span>_utils__WEBPACK_IMPORTED_MODULE_0__<span class="token punctuation">[</span><span class="token string">'isNull'</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token punctuation">}</span><span class="token punctuation">,</span>
<span class="token string">'./src/utils.js'</span><span class="token punctuation">:</span> <span class="token keyword">function</span><span class="token punctuation">(</span>module<span class="token punctuation">,</span> __webpack_exports__<span class="token punctuation">,</span> __webpack_require__<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token string">'use strict'</span><span class="token punctuation">;</span>
    __webpack_require__<span class="token punctuation">.</span><span class="token function">r</span><span class="token punctuation">(</span>__webpack_exports__<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">/* harmony export (binding) */</span> __webpack_require__<span class="token punctuation">.</span><span class="token function">d</span><span class="token punctuation">(</span>__webpack_exports__<span class="token punctuation">,</span> <span class="token string">'isNull'</span><span class="token punctuation">,</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> isNull<span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">/* harmony export (binding) */</span> __webpack_require__<span class="token punctuation">.</span><span class="token function">d</span><span class="token punctuation">(</span>__webpack_exports__<span class="token punctuation">,</span> <span class="token string">'isNumber'</span><span class="token punctuation">,</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> isNumber<span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">function</span> <span class="token function">isNull</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'isNull'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token keyword">null</span> <span class="token operator">===</span> obj<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">function</span> <span class="token function">isNumber</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'isNumber'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">return</span> <span class="token keyword">typeof</span> obj <span class="token operator">===</span> <span class="token string">'number'</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们发现<code>index.js</code>的打包结果中，只保留了<code>isNull</code>的使用，而虽然我们同时<code>import</code>了<code>isNumber</code>和<code>isNull</code>，但最终<code>isNumber</code>并没有出现在<code>index.js</code>的打包结果内：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token keyword">function</span><span class="token punctuation">(</span>module<span class="token punctuation">,</span> __webpack_exports__<span class="token punctuation">,</span> __webpack_require__<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token string">'use strict'</span><span class="token punctuation">;</span>
    <span class="token comment">// 注意！注意！注意！</span>
    <span class="token comment">// 注意这里打包后_utils__WEBPACK_IMPORTED_MODULE_0__</span>
    __webpack_require__<span class="token punctuation">.</span><span class="token function">r</span><span class="token punctuation">(</span>__webpack_exports__<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">/* harmony import */</span> <span class="token keyword">var</span> _utils__WEBPACK_IMPORTED_MODULE_0__ <span class="token operator">=</span> <span class="token function">__webpack_require__</span><span class="token punctuation">(</span>
        <span class="token comment">/*! ./utils */</span> <span class="token string">'./src/utils.js'</span>
    <span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token function">Object</span><span class="token punctuation">(</span>_utils__WEBPACK_IMPORTED_MODULE_0__<span class="token punctuation">[</span><span class="token string">'isNull'</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">但是<code>utils.js</code>打包后的内容没有变化，保留了<code>isNumber</code>的方法。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">这说明，Webpack 的 Tree-Shaking 第一步只不过是去掉了无用的引用，但是并没有删除无用的代码，删除无用的代码是<code>mode=production</code>时候使用压缩工具实现的。那么我们在使用<code>webpack --mode=production</code>来看下结果，格式化后，我们看到<code>isNumber</code>部分的关键字没有了（因为有<code>console.log('isNumber')</code>，可以搜索<code>isNumber</code>字符串关键字）：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token operator">!</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">var</span> t <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
    <span class="token comment">//... 忽略内容</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    <span class="token number">9</span><span class="token punctuation">:</span> <span class="token keyword">function</span><span class="token punctuation">(</span>e<span class="token punctuation">,</span> t<span class="token punctuation">,</span> r<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token string">'use strict'</span><span class="token punctuation">;</span>
        r<span class="token punctuation">.</span><span class="token function">r</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">,</span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'isNull'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">到此，我们已经理解 Tree-Shaking 的原理和使用方法了。</p>
</div><div class="cl-preview-section"><h2 id="tree-shaking-并不是银弹" style="font-size: 30px;">Tree-Shaking 并不是银弹</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">通过上面的实验，可能大家认为 Tree-Shaking 已经很了不起了，可以帮助我们缩减代码，但是很多情况下 Tree-Shaking 并不是银弹！首先基于 Tree-Shaking 的原理，所以我们的代码必须遵循 ES6 的模块规范，即使用 <code>import</code> 和 <code>export</code>语法，如果是 CommonJS 规范（使用<code>require</code>）则无法使用 Tree-Shaking 功能。除了这点之外，在使用 Tree-Shaking 还有什么注意点或者 Tree-Shaking 处理不到的地方呢？</p>
</div><div class="cl-preview-section"><h3 id="tree-shaking-处理-class">Tree-Shaking 处理 Class</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">下面我们再来看下 Tree-Shaking 对类的处理，首先创建一个<code>class.js</code>，内容如下：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token comment">// class.js</span>
<span class="token keyword">class</span> <span class="token class-name">Utils</span> <span class="token punctuation">{</span>
    <span class="token function">foo</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'foo'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token function">bar</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'bar'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">export</span> <span class="token keyword">default</span> Utils<span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">然后我们在<code>class-entry.js</code>中引入这个<code>Class</code>，并且只是用<code>foo</code>的方法：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token comment">// class-entry.js</span>
<span class="token keyword">import</span> Utils <span class="token keyword">from</span> <span class="token string">'./class'</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> u <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Utils</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>u<span class="token punctuation">.</span><span class="token function">foo</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们希望 Tree-Shaking 能够帮我们把不使用的<code>bar</code>方法干掉，但是实际 Tree-Shaking 做不了这样的事情：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token keyword">function</span><span class="token punctuation">(</span>e<span class="token punctuation">,</span> t<span class="token punctuation">,</span> o<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token string">'use strict'</span><span class="token punctuation">;</span>
    o<span class="token punctuation">.</span><span class="token function">r</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">const</span> n <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">class</span> <span class="token punctuation">{</span>
        <span class="token function">foo</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'foo'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token function">bar</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'bar'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>n<span class="token punctuation">.</span><span class="token function">foo</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">这表明 webpack Tree-Shaking 只处理顶层内容，例如类和对象内部都不会再被分别处理，这主要也是由于 JavaScript 的动态语言特性所致，例如下面的代码：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token keyword">import</span> Utils <span class="token keyword">from</span> <span class="token string">'./class'</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> u <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Utils</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>u<span class="token punctuation">[</span>Math<span class="token punctuation">.</span><span class="token function">random</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&gt;</span> <span class="token number">0.5</span> <span class="token operator">?</span> <span class="token string">'foo'</span> <span class="token punctuation">:</span> <span class="token string">'bar'</span><span class="token punctuation">]</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">JavaScript 的编译器并不能识别一个方法名字究竟是以直接调用的形式出现（<code>u.foo()</code>）还是以字符串的形式（<code>u['foo']()</code>）或者其他更加离奇的方式。因此误删方法只会导致运行出错，反而得不偿失。</p>
</div><div class="cl-preview-section"><h3 id="副作用（side-effect）代码">副作用（Side Effect）代码</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">知道函数式编程的朋友都会知道<strong>副作用</strong>（Side Effect）这个词，副作用会在我们项目中频繁的出现。我们称模块（函数）具有副作用，就是说这个模块是不纯的，这里可以引入纯函数的概念：</p>
</div><div class="cl-preview-section"><blockquote>
<p style="font-size: 20px; line-height: 38px;">对于相同的输入就有相同的输出，不依赖外部环境，也不改变外部环境。</p>
</blockquote>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">符合上面描述的函数就可以称为<strong>纯函数</strong>，不符合就是不纯的，不纯就具有副作用的，是可能对外界造成影响的。我们通过代码示例来理解下：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token comment">// 函数内调用外部方法</span>
<span class="token keyword">import</span> <span class="token punctuation">{</span>isNumber<span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'lodash-es'</span><span class="token punctuation">;</span>
<span class="token keyword">export</span> <span class="token keyword">function</span> <span class="token function">foo</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token function">isNumber</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token comment">// 直接使用全局对象</span>
<span class="token keyword">function</span> <span class="token function">goto</span><span class="token punctuation">(</span>url<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    location<span class="token punctuation">.</span>href <span class="token operator">=</span> url<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token comment">// 直接修改原型</span>
Array<span class="token punctuation">.</span>prototype<span class="token punctuation">.</span><span class="token function-variable function">hello</span> <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token string">'hello'</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">上面几种方式的代码都是有副作用的代码，这样的代码在 Webpack 中因为并不知道代码内部究竟做了什么事情，所以不会被 Tree-Shaking 删除。那么怎么解决副作用呢？有两种方式：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">代码中消除副作用；</li>
<li style="font-size: 20px; line-height: 38px;">配置<code>sideEffects</code>告诉 webpack 模块是安全的，不会带有副作用，可以放心优化。</li>
</ol>
</div><div class="cl-preview-section"><h4 id="代码中消除副作用" style="font-size: 26px;">代码中消除副作用</h4>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">例如我们按照纯函数的定义，可以将需要用到的方法通过参数的方式传入：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token comment">// 函数内调用外部方法</span>
<span class="token keyword">export</span> <span class="token keyword">function</span> <span class="token function">foo</span><span class="token punctuation">(</span>isNumber<span class="token punctuation">,</span> obj<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token function">isNumber</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token comment">// 直接使用全局对象</span>
<span class="token keyword">function</span> <span class="token function">goto</span><span class="token punctuation">(</span>location<span class="token punctuation">,</span> url<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    location<span class="token punctuation">.</span>href <span class="token operator">=</span> url<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><h4 id="配置sideeffects" style="font-size: 26px;">配置<code>sideEffects</code></h4>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">Webpack 的项目中，可以在<code>package.json</code>中使用<code>sideEffects</code>来告诉 webpack 哪些文件中的代码具有副作用，从而对没有副作用的文件代码可以放心的使用 Tree-Shaking 进行优化。</p>
</div><div class="cl-preview-section"><pre class="  language-json"><code class="prism  language-json"><span class="token comment">// package.json</span>
<span class="token punctuation">{</span>
    <span class="token string">"name"</span><span class="token punctuation">:</span> <span class="token string">"tree-shaking-side-effect"</span><span class="token punctuation">,</span>
    <span class="token string">"sideEffects"</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">"./src/utils.js"</span><span class="token punctuation">]</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">如果自己的项目是个类库或者工具库，需要发布给其他项目使用，并且项目是使用 ES6 Modules 编写的，没有副作用，那么可以在该项目<code>package.json</code>设置<code>sideEffects:false</code>来告诉使用该项目的 webpack 可以放心的对该项目进行 Tree-Shaking，而不必考虑副作用。</p>
</div><div class="cl-preview-section"><h2 id="总结" style="font-size: 30px;">总结</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">Tree-Shaking 对前端项目来说可谓意义重大，是一个极致优化的理想世界，是前端进化的又一个终极理想。但是理想是美好的，现实是骨感的，真正发挥 Tree-Shaking 的强大作用，还需要我们在日常的代码中保持良好的开发习惯：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">要使用 Tree-Shaking 必然要保证引用的模块都是 ES6 规范的，很多工具库或者类库都提供了 ES6 语法的库，例如 lodash 的 ES6 版本是<code>lodash-es</code>；</li>
<li style="font-size: 20px; line-height: 38px;">按需引入模块，避免「一把梭」，例如我们要使用 lodash 的<code>isNumber</code>，可以使用<code>import isNumber from 'lodash-es/isNumber';</code>，而不是<code>import {isNumber} from 'lodash-es'</code>；</li>
<li style="font-size: 20px; line-height: 38px;">减少代码中的副作用代码。</li>
</ol>
</div><div class="cl-preview-section"><blockquote>
<p style="font-size: 20px; line-height: 38px;">Tips：另外一些组件库，例如 AntDesign 和 ElementUI 这些组件库，本身自己开发了 <a href="https://www.npmjs.com/package/babel-plugin-import">Babel 的插件</a>，通过插件的方式来按需引入模块，避免一股脑的引入全部组件。</p>
</blockquote>
</div><div class="cl-preview-section"><blockquote>
<p style="font-size: 20px; line-height: 38px;">本小节 Webpack 相关面试题：</p>
<ol>
<li style="font-size: 20px; line-height: 38px;">什么是 Tree-Shaking？</li>
<li style="font-size: 20px; line-height: 38px;">怎么在 Webpack 中做 Tree-Shaking？</li>
<li style="font-size: 20px; line-height: 38px;">Webpack 中 Tree-Shaking 应该注意什么？</li>
</ol>
</blockquote>
</div></div>
            </div>
                            <!-- 买过的阅读 -->
                <div class="art-next-prev clearfix">
                                                                        <!-- 已买且开放 或者可以试读 -->
                            <a href="/read/29/article/278">
                                                    <div class="prev l clearfix">
                                <div class="icon l">
                                    <i class="imv2-arrow3_l"></i>
                                </div>
                                <p>
                                    20 Webpack 优化之速度优化
                                </p>
                            </div>
                        </a>
                                                                                            <!-- 已买且开放 或者可以试读 -->
                            <a href="/read/29/article/280">
                                                    <div class="next r clearfix">
                                <p>
                                    22 为你准备了一份 Webpack 工程化最佳实践总结
                                </p>
                                <div class="icon r">
                                    <i class="imv2-arrow3_r"></i>
                                </div>

                            </div>
                        </a>
                                    </div>
                    </div>
        <div class="comments-con js-comments-con" id="coments_con">     <div class="number">精选留言 <span class="js-number">0</span></div>     <div class="comments">         <div class="input-fake js-showcommentModal">             欢迎在这里发表留言，作者筛选后可公开显示         </div>                      <div class="noData">                 <p>                     <i class="imv2-error_c"></i>                 </p>                 <p>目前暂无任何讨论</p>             </div>              </div>  </div>



    </div>
    
    
    

</div>
 
<!-- 专栏介绍页专栏评价 -->

<!-- 专栏介绍页底部三条评价 -->

<!-- 专栏阅读页弹层目录和介绍页页面目录 -->

<!-- 专栏阅读页发布回复 -->

<!-- 专栏阅读页发布评论 -->

<!-- 专栏阅读页底部评论 -->

<!-- 专栏阅读 单个 评论 -->

<!-- 新增回复和展开三条以外回复 -->

<!-- 立即订阅的弹窗 -->












</div></body></html>